package com.crland;

import com.crland.entity.MemberInfo;
import com.crland.entity.oc.OcMemberInfo;
import com.crland.service.MemberInfoService;
import com.crland.service.impl.MemberInfoServiceImpl;
import com.crland.service.oc.OcMemberInfoService;
import com.crland.service.oc.impl.OcMemberServiceImpl;
import com.crland.tools.GetPicture;
import com.crland.tools.LinuxExec;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Main {
    private static Logger logger = LoggerFactory.getLogger(Main.class);

    private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public static void main(String[] args) {
        MemberInfoService memberInfoService =new MemberInfoServiceImpl();
        OcMemberInfoService ocMemberInfoService = new OcMemberServiceImpl();
        LinuxExec linuxExec = new LinuxExec();
        int limit = 1000;
        String count = ocMemberInfoService.count();
        int countInt = Integer.parseInt(count);
        int pageSize = countInt/limit;
        Set<String> idSet =  memberInfoService.allIdSet();
        String arg= "";
        if (args.length >0){
            for (int i=0;i<args.length;i++){
                arg = args[i];
            }
            if ("all".equals(arg)){
                memberInfoService.reset();
            }
        }
        //分页遍历oc中的视图
        for (int i=0;i<pageSize;i++){
            final int index = i*1000;
            final int num = limit;
            final Set<String> ownIdSet = idSet;
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    MemberInfoService memberInfoService =new MemberInfoServiceImpl();
                    OcMemberInfoService ocMemberInfoService = new OcMemberServiceImpl();
                    GetPicture getPicture = new GetPicture();
                    //分页查询4
                    List<OcMemberInfo> ocMemberInfoList = ocMemberInfoService.selectAll(index,num);
                    //遍历第i页中的所有ocMemberInfo
                    for (OcMemberInfo ocMemberInfo:ocMemberInfoList){
                        String url = ocMemberInfo.getPictureUrl();
                        String id = ocMemberInfo.getMemberId();
                        String filename = id + ".jpg";
                        String status = ocMemberInfo.getMemberStatus();
                        MemberInfo memberInfo1 = new MemberInfo();
                        if (ownIdSet.contains(id)){
                            MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(id);
                            if (StringUtil.isNotBlank(memberInfo.getId())) {
                                String oldurl = memberInfo.getUrl();
                                if (url.equals(oldurl)){
                                    if ("success".equals(memberInfo.getDownload())){
                                        logger.info("图片已存在,跳过");
                                        continue;
                                    }else {
                                        //下载
                                        try {
                                            getPicture.httpGet(url,filename);
                                            memberInfo1.setDownload("success");
                                        } catch (Exception e) {
                                            logger.error(e.toString());
                                            memberInfo1.setDownload("fail");
                                        }
                                        memberInfo1.setId(id);
                                        memberInfo1.setStatus(status);
                                        memberInfo1.setUrl(url);
                                        memberInfo1.setUpdatetime(new Date());
                                        memberInfoService.updateByPrimaryKey(memberInfo1);
                                        logger.info("会员"+id+"的图片已更新!");
                                        continue;
                                    }
                                }else {
                                    //下载
                                    try {
                                        getPicture.httpGet(url,filename);
                                        memberInfo1.setDownload("success");
                                    } catch (Exception e) {
                                        logger.error(e.toString());
                                        memberInfo1.setDownload("fail");
                                    }
                                    memberInfo1.setId(id);
                                    memberInfo1.setStatus(status);
                                    memberInfo1.setUrl(url);
                                    memberInfo1.setOldurl(oldurl);
                                    memberInfo1.setUpdatetime(new Date());
                                    memberInfoService.updateByPrimaryKey(memberInfo1);
                                    logger.info("会员"+id+"的图片已更新!");
                                    continue;
                                }
                            }
                        }
                        logger.info("开始下载会员id:"+id+"的照片");
                        try {
                            //下载
                            getPicture.httpGet(url,filename);
                            memberInfo1.setDownload("success");
                        } catch (Exception e) {
                            logger.error(e.toString());
                            memberInfo1.setDownload("fail");
                        }
                        memberInfo1.setId(id);
                        memberInfo1.setStatus(status);
                        memberInfo1.setUrl(url);
                        memberInfo1.setCreatetime(new Date());
                        memberInfoService.insert(memberInfo1);
                    }
                }
            });
        }
        fixedThreadPool.shutdown();
        while (true) {
            if (fixedThreadPool.isTerminated()) {
                logger.info("所有图片下载完成!");
                break;
            }
            try {
                logger.info("正在下载图片...'");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.error(e.toString());
            }
        }
        linuxExec.exec("./aitool -type all -input ./pictures -output ./comm/ && rm -rf ./pictures/*");
    }
}
